<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/12/14/014
 * Time: 15:55
 */

namespace app\api\model;


use app\api\service\Token;
use app\api\model\Member as MemberModel;
use app\api\service\Order as OrderService;
use app\api\service\NoteCode as NoteCodeService;
use app\api\model\Config as ConfigModel;
use app\lib\exception\MemberException;
use think\Db;
use think\Exception;

class MemberWithdraw extends BaseModel {

    /**
     * 申请提现
     * @param $params
     * @throws Exception
     * @throws MemberException
     */
    public static function applyWithdraw($params) {
        $uid = Token::getCurrentUid();
        $member = MemberModel::get(['id' => $uid]);
        if ($params['money'] > $member['money']) {
            throw new MemberException([
                'msg' => '账户余额不足！',
                'errotCode' => 30002
            ]);
        }

        $withdraw_sn = OrderService::makeOrderNo('TX');
        $data = [
            'member_id' => $uid,
            'account_to_be_credited_type' => $params['account_to_be_credited_type'],
            'money' => (int)$params['money'],
            'withdraw_sn' => $withdraw_sn
        ];
        if ($params['account_to_be_credited_type'] == 1) {
            $data['member_bank_id'] = $params['member_bank_id'];
        }
        Db::startTrans();
        try {
            self::create($data);
            // 提现申请成功 更新账户余额
            $member->setDec('money', $params['money']);
            MemberBill::add_member_bill($uid, $params['money'], '提现', 4, $withdraw_sn, 'member_withdraw',  '提现');
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            throw $e;
        }

        // 短信通知
        $part_order_number = ConfigModel::get(['name' => 'enter_apply_for_inform_number']);
        $manage_mobile = $part_order_number['value'];
        $param = [
            'mobile' => $manage_mobile,
            'order_sn' => $withdraw_sn,
            'type' => 12,
            'price' => $params['money'],
            'username' => $member['username'],
        ];
        NoteCodeService::send_code($param);

    }

}